using System;
using System.Globalization;
using Reactor.Environment;
using Reactor.ServiceGrid.Packages;
using Reactor.ServiceGrid.Resources;
using Reactor.ServiceGrid.Utility;

namespace Reactor.ServiceGrid.Repositories
{
    public class PackageRepositoryFactory : IPackageRepositoryFactory
    {
        private readonly IProgressReporter _progressReporter;

        #region Constructors

        /// <summary>
        /// Initializes the <see cref="PackageRepositoryFactory"/> class.
        /// </summary>
        static PackageRepositoryFactory()
        {
            Default = new PackageRepositoryFactory();
        }

        #endregion

        public static PackageRepositoryFactory Default { get; private set; }

        public IPackageRepository CreateRepository(string source)
        {
            var packageSource = new PackageSource(source);
            return CreateRepository(packageSource);
        }

        /// <summary>
        /// Creates a package repository based on the source of the package.
        /// </summary>
        /// <param name="packageSource">The package source.</param>
        /// <returns><list type="table"><listheader>Possible Returns</listheader>
        /// <item><seealso cref="LocalPackageRepository"/> if source is a file URI.</item>
        /// <item><seealso cref="DataServicePackageRepository"/> if source is a HTTP URI.</item></list></returns>
        public virtual IPackageRepository CreateRepository(PackageSource packageSource)
        {
            if (packageSource == null) throw new ArgumentNullException("packageSource");
            if (packageSource.IsAggregate) throw new NotSupportedException();

            // First check for DB flag as source. If present, create sql repository
            //  against default Reactor database
            if (packageSource.Source.ToLower() == "db")
                Context.ServiceLocator.RegisterType<IPackageRepository, SqlPackageRepository>();
            else
            {
                var uri = new Uri(packageSource.Source);
                if (uri.IsFile)
                    Context.ServiceLocator.RegisterInstance<IPackageRepository>(new LocalPackageRepository(uri.LocalPath));
            }

            return Context.ServiceLocator.GetInstance<IPackageRepository>();
        }
    }
}
